package com.css.apps.base.role.action;

import com.css.apps.base.org.model.SUserOrg;
import com.css.apps.base.user.model.SUser;
import com.css.core.configuration.Environment;
import com.css.db.query.QueryCache;
import com.css.util.Ajax;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.UserAction;
import com.opensymphony.xwork.Action;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;

/**
 * <p>
 * 获得组织机构-用户树
 * </p>
 * 
 */
@SuppressWarnings("serial")
public class GetOrgUserJson extends UserAction {
	private static Log log = LogFactory.getLog(GetOrgUserJson.class);
	private String orgId;
	private String roleId;

	@SuppressWarnings("unchecked")
	@Override
	protected String userGo() {
		try {
			if (StringHelper.isEmpty(orgId)) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
				return ERROR;
			}
			List<String> userIdList = new QueryCache("select distinct a.userId from SUserRole a where a.roleId = :roleId")
					.setParameter("roleId", roleId).list();
			result = getUserJsonByOrgIdList(orgId,userIdList).toString();
			return SUCCESS;
		} catch (Exception ex) {
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.exception"));
			log.error(ex.getMessage(), ex);
			return Action.ERROR;
		}
	}

	@SuppressWarnings("unchecked")
	public static JSONArray getUserJsonByOrgIdList(String orgId, List<String> userIdList) {
		JSONArray jaTree = new JSONArray();
		List<String> sUserOrgIds = new QueryCache("select a.uuid from SUserOrg  a where a.deptId=:orgId ")
				.setParameter("orgId", orgId).list();
		List<SUserOrg> list = QueryCache.idToObj(SUserOrg.class, sUserOrgIds);
		if (list != null) {
			for (SUserOrg uo : list) {
				SUser u = QueryCache.get(SUser.class, uo.getUserId());
				if(u==null || userIdList.contains(u.getUuid())){
					continue;
				}
				JSONObject one = new JSONObject();
				one.put("id", u.getUserId());
				one.put("name", u.getRealName());
				one.put("pId", orgId);
				one.put("type", "user");
				one.put("isParent", false);
				jaTree.add(one);
			}
		}
		return jaTree;
	}

	public String getOrgId() {
		return orgId;
	}

	public void setOrgId(String orgId) {
		this.orgId = orgId;
	}

	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}
}
